﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BUS;
using System.Collections;
using DevExpress.XtraGrid.Views.Grid;
using Aspose.Cells;

namespace GUI
{
    public partial class Form_TaoDonDatHang : UserControl
    {
        DonDatHangBUS _BUS = new DonDatHangBUS();
        NhanVienBUS _BUSNV = new NhanVienBUS();
        ChiTietDonDatHangBUS _BUSCT = new ChiTietDonDatHangBUS();
        SanPhamBUS _BUSSP = new SanPhamBUS();
        List<ChiTietDonDatHang> LstEmty = null;
        DonDatHang objMain = null;
        float CK = 0;
        float T = 0;
        public Form_TaoDonDatHang()
        {
            InitializeComponent();
            Init();
        }
        public void Init()
        {
            radioGroup_TT.EditValue = 1;
            textEdit_NgayDat.DateTime = DateTime.Now;
            lookUpEdit_ListDDH.Properties.DataSource = _BUS.GetList();
            lookUpEdit_NguoiDat.Properties.DataSource = _BUSNV.GetData();
            repositoryItemLookUpEdit_SP.DataSource = _BUSSP.GetData();
            repositoryItemLookUpEdit_SP2.DataSource = repositoryItemLookUpEdit_SP.DataSource;
            LstEmty = _BUSCT.GetListEmty();
            gridControl_CTDatHang.DataSource = LstEmty;
            CK = _BUS.GetChietKhau();
            T = _BUS.GetVAT();


            textEdit_CK.TextChanged += new EventHandler(textEdit_CK_TextChanged);
            textEdit_SubSP.TextChanged += new EventHandler(textEdit_SubSP_TextChanged);

            textEdit_SubSPSauCK.TextChanged += new EventHandler(textEdit_SubSPSauCK_TextChanged);
            textEdit_SubTL.TextChanged += new EventHandler(textEdit_SubSPSauCK_TextChanged);

            textEdit_SubTotal.TextChanged += new EventHandler(textEdit_SubTotal_TextChanged);
            textEdit_Thue.TextChanged += new EventHandler(textEdit_Thue_TextChanged);
        }

        void textEdit_CK_TextChanged(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            float tmp = Utils.ToFloat(textEdit_SubSP.Text) - Utils.ToFloat(textEdit_CK.Text);
            textEdit_SubSPSauCK.Text = Utils.ToStr(tmp);
        }

        void textEdit_Thue_TextChanged(object sender, EventArgs e)
        {
            float tmp = Utils.ToFloat(textEdit_SubTotal.Text) + Utils.ToFloat(textEdit_Thue.Text);
            textEdit_SubVAT.Text = Utils.ToStr(tmp);
        }

        void textEdit_SubTotal_TextChanged(object sender, EventArgs e)
        {
            float tmp = Utils.ToFloat(textEdit_SubTotal.Text) * T ;
            textEdit_Thue.Text = Utils.ToStr(tmp);
        }

        void textEdit_SubSPSauCK_TextChanged(object sender, EventArgs e)
        {
            float tmp = Utils.ToFloat(textEdit_SubSPSauCK.Text) + Utils.ToFloat(textEdit_SubTL.Text);
            textEdit_SubTotal.Text = Utils.ToStr(tmp);
        }

        void textEdit_SubSP_TextChanged(object sender, EventArgs e)
        {
            //throw new NotImplementedException();
            float tmp = Utils.ToFloat(textEdit_SubSP.Text) * CK;
            textEdit_CK.Text = Utils.ToStr(tmp);
        }
        private void textEdit11_EditValueChanged(object sender, EventArgs e)
        {
               
        }

        private void lookUpEdit_ListDDH_EditValueChanged(object sender, EventArgs e)
        {
            if (lookUpEdit_ListDDH.ItemIndex == -1)
                return;
            DonDatHang obj = (DonDatHang) lookUpEdit_ListDDH.GetSelectedDataRow();
            objMain = obj;
            gridControl_CTDatHang.DataSource = _BUSCT.GetListFromDDH(obj);

            lookUpEdit_NguoiDat.EditValue = obj.NguoiLap;
            textEdit_NgayDat.DateTime = obj.NgayDat;
            
            textEdit_SubSP.Text = Utils.ToStr(obj.SubSP);           
            textEdit_SubTL.Text = Utils.ToStr(obj.SubTL);           
            radioGroup_TT.EditValue = obj.PhuongThucTT;
        }

        private void simpleButton_DonMoi_Click(object sender, EventArgs e)
        {
            objMain = null;
            lookUpEdit_ListDDH.EditValue = null;
            gridControl_CTDatHang.DataSource = LstEmty;

            lookUpEdit_NguoiDat.EditValue = null;
            textEdit_NgayDat.DateTime = DateTime.Now;
            textEdit_CK.Text = string.Empty;
            textEdit_SubSP.Text = string.Empty;
            textEdit_SubSPSauCK.Text = string.Empty;
            textEdit_SubTL.Text = string.Empty;
            textEdit_SubTotal.Text = string.Empty;
            textEdit_SubVAT.Text = string.Empty;
            textEdit_Thue.Text = string.Empty;
            radioGroup_TT.EditValue = 1;
            textEdit_MaStockist.Text = string.Empty;
            textEdit_DiaChi.Text = string.Empty;
        }

        private void simpleButton_XoaDon_Click(object sender, EventArgs e)
        {
            if (lookUpEdit_ListDDH.EditValue == null || string.IsNullOrEmpty(lookUpEdit_ListDDH.EditValue.ToString()))
                return;
            DonDatHang obj = (DonDatHang)lookUpEdit_ListDDH.GetSelectedDataRow();
           
            if (MessageBox.Show("Bạn có muốn xóa ?", "Thông Báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                return;
            if (_BUS.Delete(obj))
            {
                IList lst = (IList)lookUpEdit_ListDDH.Properties.DataSource;
                lookUpEdit_ListDDH.EditValue = null;
                lst.Remove(obj);
                simpleButton_DonMoi_Click(null, null);
                MessageBox.Show("Xóa Đặt Hàng Thành Công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Xóa Đặt Hàng Thất Bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            GridView _view = (GridView)sender;
            int []n = _view.GetSelectedRows();
            if (n.Length > 0)
            {
                ChiTietDonDatHang op = (ChiTietDonDatHang)_view.GetRow(n[0]);
                op.ThanhTien = op.DonGia * op.SoLuong;
                float tmpSP = 0;
                float tmpTL = 0;
                for (int i = 0; i < _view.RowCount; i++ )
                {
                    ChiTietDonDatHang opp = (ChiTietDonDatHang)_view.GetRow(i);
                    if (opp.CV > 0)
                        tmpSP += opp.ThanhTien;
                    else
                        tmpTL += opp.ThanhTien;
                }
                textEdit_SubSP.Text = Utils.ToStr(tmpSP);
                textEdit_SubTL.Text = Utils.ToStr(tmpTL);
            }
        }

        private void simpleButton_TaoDon_Click(object sender, EventArgs e)
        {
            if (!CheckData())
                return;
            DonDatHang obj = new DonDatHang();
            obj.NgayDat = textEdit_NgayDat.DateTime;
            //obj.TongTien = Utils.ToFloat(textEdit_SubVAT.Text);
            obj.NguoiLap = Utils.ToStr(lookUpEdit_NguoiDat.EditValue);
            obj.PhuongThucTT =  Utils.ToInt(radioGroup_TT.EditValue);
            obj.SubSP = Utils.ToFloat(textEdit_SubSP.Text);
            obj.SubTL = Utils.ToFloat(textEdit_SubTL.Text);
            
            obj.LstChiTietDonDatHang = new List<ChiTietDonDatHang>();
            GridView _view = (GridView) gridControl_CTDatHang.MainView;
            for (int i = 0; i < _view.RowCount; i++)
            {
                ChiTietDonDatHang tmp = (ChiTietDonDatHang)_view.GetRow(i);
                if (!checkSL(tmp.SoLuong))
                    return;
                ChiTietDonDatHang objtmp = new ChiTietDonDatHang();
                objtmp.MaSP = tmp.MaSP;
                objtmp.SoLuong = tmp.SoLuong;
                objtmp.ThanhTien = tmp.ThanhTien;
                objtmp.DonGia = tmp.DonGia;
                objtmp.CV = tmp.CV;
                obj.LstChiTietDonDatHang.Add(objtmp);
            }
            if (_BUS.Insert(obj))
            {
                IList lst = (IList)lookUpEdit_ListDDH.Properties.DataSource;
                lst.Add(obj);
                lookUpEdit_ListDDH.EditValue = obj.MaDDH;
                MessageBox.Show("Thêm Đơn Đặt Hàng Thành Công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
                MessageBox.Show("Thêm Đơn Đặt Hàng Thất Bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void simpleButton_Update_Click(object sender, EventArgs e)
        {
            if (!CheckData())
                return;
            DonDatHang obj = new DonDatHang();
            obj.MaDDH = Utils.ToStr(lookUpEdit_ListDDH.EditValue);
            obj.NgayDat = textEdit_NgayDat.DateTime;
           // obj.TongTien = Utils.ToFloat(textEdit_SubVAT.Text);
            obj.NguoiLap = Utils.ToStr(lookUpEdit_NguoiDat.EditValue);
            obj.PhuongThucTT = Utils.ToInt(radioGroup_TT.EditValue);
            obj.SubSP = Utils.ToFloat(textEdit_SubSP.Text);
            obj.SubTL = Utils.ToFloat(textEdit_SubTL.Text);
            obj.LstChiTietDonDatHang = new List<ChiTietDonDatHang>();
            GridView _view = (GridView)gridControl_CTDatHang.MainView;
            for (int i = 0; i < _view.RowCount; i++)
            {
                ChiTietDonDatHang tmp = (ChiTietDonDatHang)_view.GetRow(i);
                if (!checkSL(tmp.SoLuong))
                    return;
                ChiTietDonDatHang objtmp = new ChiTietDonDatHang();
                objtmp.MaDDH = obj.MaDDH;
                objtmp.MaSP = tmp.MaSP;
                objtmp.SoLuong = tmp.SoLuong;
                objtmp.ThanhTien = tmp.ThanhTien;
                objtmp.DonGia = tmp.DonGia;
                objtmp.CV = tmp.CV;
                obj.LstChiTietDonDatHang.Add(objtmp);
            }
            if (_BUS.Update(obj))
            {
                IList lst = (IList)lookUpEdit_ListDDH.Properties.DataSource;
                DonDatHang tmp = (DonDatHang)lst[lookUpEdit_ListDDH.ItemIndex];
                tmp.NgayDat = obj.NgayDat;
                tmp.NguoiLap = obj.NguoiLap;
               // tmp.TongTien = obj.TongTien;
                tmp.PhuongThucTT = obj.PhuongThucTT;
                tmp.SubSP = Utils.ToInt(textEdit_SubSP.Text);
                tmp.SubTL = Utils.ToInt(textEdit_SubTL.Text);
                lookUpEdit_ListDDH.EditValue = obj.MaDDH;
                MessageBox.Show("Sửa Đơn Đặt Hàng Thành Công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Sửa Đơn Đặt Hàng Thất Bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void simpleButton_Export_Click(object sender, EventArgs e)
        {
            SaveFileDialog file = new SaveFileDialog();
            file.FileName = "DonDatHang.xls";
            file.DefaultExt = "xls";
            file.Filter = "Excel Files (*.xls, *xlsx)|*.xls;*xlsx|All Files (*.*)|*.*";
            if (file.ShowDialog() == DialogResult.OK)
            {
                string FileName = file.FileName;
                Cursor = Cursors.WaitCursor;
                Workbook book = new Workbook();
                try
                {
                    book.Open("Template\\DatHangTemplate.xls");
                }
                catch (System.Exception ex)
                {
                    Cursor = Cursors.WaitCursor;
                    MessageBox.Show("Không Thể Xuất File Excel", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                Worksheet sheet = book.Worksheets["DonDatHang"];
                sheet.Cells["B2"].PutValue(textEdit_MaStockist.Text);
                sheet.Cells["B3"].PutValue(lookUpEdit_NguoiDat.Text);
                sheet.Cells["B4"].PutValue(radioGroup_TT.Text == "1" ? "Tiền Mặt" : "Thanh Toán");
                sheet.Cells["F2"].PutValue(textEdit_DiaChi.Text);
                sheet.Cells["F3"].PutValue(textEdit_NgayDat.DateTime.ToString("dd/MM/yyyy HH:mm"));
                sheet.Cells["B10"].PutValue(textEdit_SubSP.Text);
                sheet.Cells["B11"].PutValue(textEdit_CK.Text);
                sheet.Cells["B12"].PutValue(textEdit_SubSPSauCK.Text);
                sheet.Cells["B13"].PutValue(textEdit_SubTL.Text);
                sheet.Cells["B14"].PutValue(textEdit_SubTotal.Text);
                sheet.Cells["B15"].PutValue(textEdit_Thue.Text);
                sheet.Cells["B16"].PutValue(textEdit_SubVAT.Text);


                int r = sheet.Cells["A8"].Row;
                GridView view = (GridView)gridControl_CTDatHang.MainView;
                sheet.Cells.InsertRows(r+1, view.RowCount-1);
                for (int i = 0; i < view.RowCount; i++)
                {
                    ChiTietDonDatHang ctdh = (ChiTietDonDatHang)view.GetRow(i);
                    sheet.Cells["A" + (i + r+1).ToString()].PutValue(view.GetRowCellDisplayText(i, gridColumn_MaSP));
                    sheet.Cells["B" + (i + r+1).ToString()].PutValue(view.GetRowCellDisplayText(i, gridColumn_TenSP));
                    sheet.Cells["C" + (i + r+1).ToString()].PutValue(view.GetRowCellDisplayText(i, gridColumn_CV));
                    sheet.Cells["D" + (i + r+1).ToString()].PutValue(view.GetRowCellDisplayText(i, gridColumn_DonGia));
                    sheet.Cells["E" + (i + r+1).ToString()].PutValue(view.GetRowCellDisplayText(i, gridColumn_SL));
                    sheet.Cells["F" + (i + r+1).ToString()].PutValue(view.GetRowCellDisplayText(i, gridColumn_TT));
                }
                try
                {
                    book.Save(FileName);
                    MessageBox.Show("Xuất File Thành Công", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch(Exception ex)
                {
                    MessageBox.Show("Xuất File Thất Bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Cursor = Cursors.Default;
            }
        }
        public bool checkSL(int i)
        {
            if (i < 0)
            {
                MessageBox.Show("Số Lượng Không Hợp Lệ", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            else
                return true;
        }
        public bool CheckData()
        {
            bool flag = true;
            if (string.IsNullOrEmpty(Utils.ToStr( lookUpEdit_NguoiDat.EditValue)))
            {
                MessageBox.Show("Chưa Chọn Người Đặt", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                flag = false;
            }
            if (Utils.ToFloat(textEdit_SubTotal.Text) <= 0)
            {
                MessageBox.Show("Chưa Nhập Số Lượng Hàng", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                flag = false;
            }
            return flag;
        }
    }
}
